package com.liurong.quartz.action;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.liurong.quartz.util.JobMonitorUtil;
import com.liurong.quartz.util.entity.JobEntity;
import com.liurong.util.redis.RedisTemplate;

/**
 * 定时任务控制类
 * 
 * @author liurong
 *
 */
@Controller
@RequestMapping("quartz")
public class QuartzController {
	private static final Logger logger = LoggerFactory.getLogger(QuartzController.class);
	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 获取所有的定时任务里列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("scheduler_list")
	public ModelAndView getSchedulerList() {
		logger.info("获取当前的定时任务-------------");
		StringBuilder keyPattern = new StringBuilder();
		keyPattern.append("jedis_lock_jobNameMapStr");
		keyPattern.append(":");
		keyPattern.append("*");
		Set<String> keys = redisTemplate.keys(keyPattern.toString());
		String jobNameMapStr = null;
		Map<String, JobEntity> jobNameMapSum = new HashMap<String, JobEntity>();
		Map<String, JobEntity> jobNameMap = null;
		for (String key : keys) {
			jobNameMapStr = redisTemplate.get(key);
			jobNameMap = JSON.parseObject(jobNameMapStr, Map.class);
			jobNameMapSum.putAll(jobNameMap);
		}
		logger.info("当前的定时任务有：" + jobNameMapSum);
		ModelAndView mav = new ModelAndView("scheduler_list");
		mav.addObject("jobNameMap", jobNameMapSum);
		return mav;
	}

	/**
	 * 暂定定时任务
	 * 
	 * @param jobName
	 *            定时任务名称
	 * @return
	 * @throws SchedulerException
	 */

	@RequestMapping("stop")
	public ModelAndView stopJob(String jobName) throws Exception {
		logger.info("暂停定时任务:**********" + jobName);
		if (StringUtils.isEmpty(jobName)) {
			logger.warn("jobName为空！");
		}
		String[] jobNameArr = jobName.split(":");
		String jobBeanName = jobNameArr[0];
		String ip = jobNameArr[1];

		redisTemplate.lpush(JobMonitorUtil.getJobLqueueStr(ip),
				JobMonitorUtil.getJobLqueueValueStr(jobBeanName, JobMonitorUtil.STOP_ACTION));

		Thread.sleep(1000);

		return new ModelAndView("redirect:/quartz/scheduler_list.do");
	}

	/**
	 * 启动定时任务
	 * 
	 * @param jobName
	 *            定时任务名称
	 * @return
	 * @throws SchedulerException
	 */

	@RequestMapping("start")
	public ModelAndView startJob(String jobName) throws Exception {
		logger.info("启动定时任务：**********" + jobName);
		if (StringUtils.isEmpty(jobName)) {
			logger.warn("jobName为空！");
		}
		String[] jobNameArr = jobName.split(":");
		String jobBeanName = jobNameArr[0];
		String ip = jobNameArr[1];

		redisTemplate.lpush(JobMonitorUtil.getJobLqueueStr(ip),
				JobMonitorUtil.getJobLqueueValueStr(jobBeanName, JobMonitorUtil.START_ACTION));

		Thread.sleep(1000);

		return new ModelAndView("redirect:/quartz/scheduler_list.do");
	}

	/**
	 * 手动启动定时任务
	 * 
	 * @param jobName
	 * @return
	 * @throws SchedulerException
	 */

	@RequestMapping("handStart")
	public ModelAndView handStartJob(String jobName) throws Exception {
		logger.info("手动启动定时任务：**********" + jobName);

		if (StringUtils.isEmpty(jobName)) {
			logger.warn("jobName为空！");
		}
		String[] jobNameArr = jobName.split(":");
		String jobBeanName = jobNameArr[0];
		String ip = jobNameArr[1];

		redisTemplate.lpush(JobMonitorUtil.getJobLqueueStr(ip),
				JobMonitorUtil.getJobLqueueValueStr(jobBeanName, JobMonitorUtil.HAND_START_ACTION));

		Thread.sleep(1000);

		return new ModelAndView("redirect:/quartz/scheduler_list.do");
	}

	/**
	 * 动态修改cron表达式
	 * 
	 * @param jobName
	 * @param cronExper
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("change_cron")
	public ModelAndView changeCron(String jobName, String cronExper) throws Exception {
		logger.info("修改执行时间：jobName=" + jobName + ",cronExper=" + cronExper);

		if (StringUtils.isEmpty(jobName)) {
			logger.warn("jobName为空！");
		}
		String[] jobNameArr = jobName.split(":");
		String jobBeanName = jobNameArr[0];
		String ip = jobNameArr[1];

		redisTemplate.lpush(JobMonitorUtil.getJobLqueueStr(ip),
				JobMonitorUtil.getJobLqueueValueStr(jobBeanName, JobMonitorUtil.CHANGE_CRON_ACTION) + ":"
						+ cronExper);

		Thread.sleep(1000);

		return new ModelAndView("redirect:/quartz/scheduler_list.do");
	}

}
